import _ from 'lodash';

function loadScript(src) {
  return new Promise((res, rej) => {
    const script = document.createElement('script');

    script.type = 'text/javascript';
    script.src = src;
    script.onload = function () {
      res();
    };
    script.onerror = function () {
      rej();
    };
    document.head.appendChild(script);
  });
}

export default function (srcs, queue = true) {
  if (_.isString(srcs)) {
    return loadScript(srcs);
  }

  if (!queue) {
    return Promise.all(srcs.map(loadScript));
  }

  return srcs.reduce((prev, src) => {
    return prev.then(() => loadScript(src));
  }, Promise.resolve());
}

